package com.gylang.sso.config;

import com.gylang.sso.exception.domian.AuthException;
import com.gylang.sso.filter.JwtAuthenticationEntryPoint;
import com.gylang.sso.filter.JwtVerifyFilter;
import com.gylang.sso.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author gylang,
 * @data 2019/12/7 13:27,
 * @DESC
 */
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RsaKeyProperties properties;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

   @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/sso/login", "/sso/logout", "/product");
    }
    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        JwtVerifyFilter jwtVerifyFilter = new JwtVerifyFilter(authenticationManager(), properties);
        jwtVerifyFilter.setRedisTemplate(redisTemplate);
        JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint = new JwtAuthenticationEntryPoint();
        httpSecurity.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/sso/login").permitAll()
                .antMatchers("/product").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .exceptionHandling()
                .accessDeniedHandler(jwtAuthenticationEntryPoint)
                .and()
                .addFilter(jwtVerifyFilter)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);


    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 使用自定义身份验证组件
        auth.authenticationProvider(new JwtAuthenticationProvider(sysUserService));
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
}
